package io.framework.modules.platform.hzt.controller;

import cn.com.digitalhainan.apione.sdk.ContentBody;
import cn.com.digitalhainan.apione.sdk.HttpCaller;
import cn.com.digitalhainan.apione.sdk.HttpParameters;
import cn.com.digitalhainan.apione.sdk.HttpReturn;
import io.framework.common.exception.ErrorCode;
import io.framework.common.exception.RenException;
import io.framework.common.utils.IpUtils;
import io.framework.common.utils.Result;
import io.framework.modules.log.entity.SysLogLoginEntity;
import io.framework.modules.log.enums.LoginOperationEnum;
import io.framework.modules.log.enums.LoginStatusEnum;
import io.framework.modules.log.service.SysLogLoginService;
import io.framework.modules.security.dto.LoginDTO;
import io.framework.modules.security.password.PasswordUtils;
import io.framework.modules.security.service.CaptchaService;
import io.framework.modules.security.service.SysUserTokenService;
import io.framework.modules.sys.dto.SysUserDTO;
import io.framework.modules.sys.enums.UserStatusEnum;
import io.framework.modules.sys.service.SysUserService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * The type Hzt uaa user controller.
 *
 * @author: dengyinghao
 * @date: 2024 /8/22 11:38
 */
@Controller
@RequestMapping("/hztuaausercontroller")
public class HztUaaUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private SysLogLoginService sysLogLoginService;

    /**
     * Uaa user detail by token string.
     *
     * @param param the param
     * @return the string
     */
    @RequestMapping(value = "/uaaUserDetailByToken", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public @ResponseBody String uaaUserDetailByToken(@RequestBody Map<String, Object> param) {
        String token = MapUtils.getString(param, "token");
        String contentJson = "";
        // 开放平台发放的accessKey
        String accessKey = "AKb6dcdd2744fd4f9ea837b8ffefa003e4";
        // 开放平台发放的secretKey
        String secretKey = "SKa0c453d7d228411182315ed88dc81307";
        // 统一认证平台的appKey
        String appKey = "AKe1238e61f33e48f1921d2bb4e562ab00";
        // api接口
        String api = "uaaUserDetailByToken";

        String region = "INTER";
        String requestUrl = "https://api-one.digitalhainan.com.cn/apione";
        ContentBody contentBody = new ContentBody(contentJson);
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", "Bearer " + token);
        header.put("Uaa-App-Key", appKey);
        header.put("Uaa-Tenant-Id", "1");
        //拼装业务信息
        HttpParameters parameters = HttpParameters.builder()
                .api(api)
                .headerParamsMap(header)
                .region(region)
                .accessKey(accessKey)
                .secretKey(secretKey)
                .contentBody(contentBody)
                .requestUrl(requestUrl)
                .build();
        //请求开发服务，获取response
        HttpReturn call = HttpCaller.getInstance().call(parameters);

        String response = call.getResponse();
        System.out.println("海政通请求的accessKey++++++++++" + accessKey);
        System.out.println("海政通请求的secretKey++++++++++" + secretKey);
        System.out.println("海政通请求的appKey++++++++++" + appKey);
        System.out.println("海政通请求的api++++++++++" + api);
        System.out.println("海政通请求的requestUrl++++++++++" + requestUrl);
        System.out.println("海政通返回++++++++++" + response);
        return response;
    }

//    @RequestMapping(value = "/getUser", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
//    @ResponseBody
//    public  Map<String,Object> getUser(@RequestBody Map<String, Object> param) {
//        String username = MapUtils.getString(param, "username");
//        Map<String,Object> map = new HashMap<>();
//        Map<String,Object> data = new HashMap<>();
//        data.put("username","xpx");
//        data.put("password","Syhb@xpx888");
//        map.put("code",200);
//        map.put("msg","success");
//        map.put("data",data);
//        return map;
//    }

    @RequestMapping(value = "/getToken", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public Result getToken(HttpServletRequest request, @RequestBody LoginDTO login) {
        SysUserDTO user = sysUserService.getByMobile(login.getPhone());

        System.out.println("user"+user.getUsername());

        SysLogLoginEntity log = new SysLogLoginEntity();
        log.setOperation(LoginOperationEnum.LOGIN.value());
        log.setCreateDate(new Date());
        log.setIp(IpUtils.getIpAddr(request));
        log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
        log.setIp(IpUtils.getIpAddr(request));

        //用户不存在
        if (user == null) {
            log.setStatus(LoginStatusEnum.FAIL.value());
            log.setCreatorName(login.getUsername());
            sysLogLoginService.save(log);
            System.out.println("user is null ");

            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //密码错误
//        if (!PasswordUtils.matches(login.getPassword(), user.getPassword())) {
//            log.setStatus(LoginStatusEnum.FAIL.value());
//            log.setCreator(user.getId());
//            log.setCreatorName(user.getUsername());
//            sysLogLoginService.save(log);
//
//            System.out.println("user is password error ");
//            throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
//        }

        //账号停用
        if (user.getStatus() == UserStatusEnum.DISABLE.value()) {
            log.setStatus(LoginStatusEnum.LOCK.value());
            log.setCreator(user.getId());
            log.setCreatorName(user.getUsername());
            sysLogLoginService.save(log);

            throw new RenException(ErrorCode.ACCOUNT_DISABLE);
        }

        //登录成功
        System.out.println("user is success ");

        log.setStatus(LoginStatusEnum.SUCCESS.value());
        log.setCreator(user.getId());
        log.setCreatorName(user.getUsername());
        sysLogLoginService.save(log);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//HH：表示24小时制，hh：表示12小时制

        String newdate = format.format(new Date());
        String date = format.format(user.getUpdateDate());
        String flag = "0";
        try {
            Date newdate1 = format.parse(newdate);
            Date date1 = format.parse(date);
            int days = (int) ((newdate1.getTime() - date1.getTime()) / (1000 * 3600 * 24));
            if (days >= 180) {
                flag = "1";
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }


        return sysUserTokenService.createToken(user.getId(), flag);
    }


}
